def merge_intervals(intervals):
    if not intervals:
        return []

    # 按照区间的起始位置进行排序
    intervals.sort(key=lambda x: x[0])

    merged = [intervals[0]]

    for i in range(1, len(intervals)):
        current_start, current_end = intervals[i]
        previous_start, previous_end = merged[-1]

        # 检查当前区间是否与上一个区间重叠
        if current_start <= previous_end:
            # 重叠，合并区间
            merged[-1] = (previous_start, max(previous_end, current_end))
        else:
            # 不重叠，直接添加当前区间
            merged.append((current_start, current_end))

    return merged

# 示例输入
intervals_input = [(1, 3), (2, 6), (8, 10), (15, 18)]

# 调用函数并输出结果
result = merge_intervals(intervals_input)
print(result)
